//
//  Snapshot.m
//  Shion
//
//  Created by Chris Karr on 12/28/07.
//  Copyright 2007-2008 Audacious Software. All rights reserved.
//

#import "Snapshot.h"
#import "DevicesModel.h";

@implementation Snapshot

@synthesize name;
@synthesize deviceStates;
@synthesize activateEvent;

- (Snapshot *) init
{
	if (self = [super init])
	{
		NSNotificationCenter * defaultCenter = [NSNotificationCenter defaultCenter];
		[defaultCenter addObserver:self selector:@selector(updateStatus:) name:DEVICE_STATUS_BROADCAST object:nil];

		self.name = @"New Snapshot";
		self.deviceStates = [NSMutableSet set];
		
		[defaultCenter postNotificationName:DEVICE_STATUS_REQUEST object:self];
	}
	
	return self;
}

- (void) updateStatus:(NSNotification *) notification
{
	NSDictionary * userInfo = [notification userInfo];
	
	for (NSDictionary * device in [userInfo valueForKey:@"devices"])
	{
		if ([device valueForKey:@"level"] != nil)
		{
			NSInteger level = [[device valueForKey:@"level"] integerValue];
			
			if (level == 0)
				[device setValue:@"Off" forKey:@"levelString"];
			else if (level < 255)
				[device setValue:[NSString stringWithFormat:@"%d", ((level + 1) / 32)] forKey:@"levelString"];
			else
				[device setValue:@"On" forKey:@"levelString"];

			[self willChangeValueForKey:@"deviceStates" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:device]];			
			[self.deviceStates addObject:device];
			[self didChangeValueForKey:@"deviceStates" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:device]];			
		}
	}

	[[NSNotificationCenter defaultCenter] removeObserver:self name:DEVICE_STATUS_BROADCAST object:nil];
}

@end
